﻿using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;

namespace umbraco.DataServices.Linq
{
    
    internal class NodeEnumerator : IEnumerator<UmbracoNode> {

        private readonly IEnumerable<XElement> _elements;
        private readonly UmbracoContext _context;
        private IEnumerator<XElement> _rawElements;
        private UmbracoNode _current;

        public IEnumerable<string> TargetAlias { get; set; }

        public NodeEnumerator(UmbracoContext context, IEnumerable<XElement> elements, string targetAlias) {
            _elements = elements;
            _context = context;
            TargetAlias = new[] { targetAlias };
            Reset();
        }

        public NodeEnumerator(UmbracoContext context, IEnumerable<XElement> elements, IEnumerable<string> targetAliases)
        {
            _elements = elements;
            _context = context;
            TargetAlias = targetAliases;
            Reset();
        }

        public UmbracoNode Bind(XElement element) {
            return new UmbracoNode(_context, element, TargetAlias);
        }

        public void Dispose() {
            _rawElements = null;
        }

        public bool MoveNext() {
            if (_rawElements == null)
                return false;
            if (_rawElements.MoveNext() == false)
                return false;
            _current = Bind(_rawElements.Current);
            return true;
        }

        public void Reset() {
            if (_elements == null)
                return;
            _rawElements = _elements.GetEnumerator();
        }

        public UmbracoNode Current {
            get { return _current; }
        }

        object IEnumerator.Current {
            get { return Current; }
        }
    }
}
